function createLobby() {
    $.address.value(makeUrl('/lobby'));
    jQuery('<div/>', {
        id:"lobby"
    }).appendTo('#canvasWrapperSelf');

    jQuery('<input/>', {
        type:"submit",
        class:"singlePlayer",
        value:"",
        onclick:"initTwoPlayerGame();"
    }).appendTo('#lobby');

    jQuery('<input/>', {
        type:"submit",
        class:"multiPlayer",
        value:"",
        onclick:"setLobbyToInterval();"
    }).appendTo('#lobby');
}

function setLobbyToInterval() {
    $.address.value(makeUrl('/multiplayer'));
    doLogin(function () {
        createOrMarkOnline(function () {
            jQuery("#lobby .singlePlayer").remove();
            jQuery("#lobby .multiPlayer").remove();
            (function loop() {
                setTimeout(function () {
                    if (!OurGame.newGameButtonPushed) {
                        startLobby();
                        loop();
                    }

                }, 5000);
            })();
        });

    });

}

function startLobby() {
    emptyLobby();
    jQuery('<input/>', {
        type:"submit",
        value:"New game",
        onclick:"$.address.value(makeUrl('/multiplayer/newgame'));",
        class:"newGame blue-btn"

    }).appendTo('#lobby');

    jQuery('<div/>', {
        id:"nrOfRunning"
    }).appendTo('#lobby');
    jQuery('#lobby #nrOfRunning').text("Running: 0");

    jQuery('<div/>', {
        id:"nrOfWaiting"
    }).appendTo('#lobby');
    jQuery('#lobby #nrOfWaiting').text("Waiting: 0");

    createScrollBarContainers("scrollbar2", "#lobby");
    jQuery('<div/>', {
        id:"waitingGames",
        class:"overview"
    }).appendTo('#scrollbar2 .viewport');

    getGamesStat(
        function (result) {
            jQuery('#lobby #nrOfRunning').text("Running: " + result['nrOfRunningGames']);
            jQuery('#lobby #nrOfWaiting').text("Waiting: " + result['nrOfWaitingGames']);
        }
    );
    getWaitingGames();
}


function getWaitingGames() {
    jQuery.ajax({
        url:"/lobby/getWaitingGames",
        success:function (data) {
            if (data.status == "FAILURE") {
                stickyError('An error occurred when getting waiting games!', "ERROR getWaitingGames: " + data.reason);
            } else {
                createWaitingGames(data);
                var oScrollbar = $('#scrollbar2');
                oScrollbar.tinyscrollbar();
                oScrollbar.tinyscrollbar_update();
            }
        },
        error:function (data) {
            error('An error occured!', "Error: " + data);
        },
        type:"get",
        timeout:30000
    });
}

function createWaitingGameDiv(data, i) {
    jQuery('<div/>', {
        id:"game" + data.waitingGames[i].gameID,
        class:"waiting",
        onclick:"joinGame('" + data.waitingGames[i].gameID + "');"
    }).appendTo('#waitingGames');
}

function createWaitingGames(data) {
    for (var i = 0; i < data.waitingGames.length; i++) {
        createWaitingGameDiv(data, i);

        for (var j = 0; j < data.waitingGames[i].itendedPlayers.length; j++) {
            createImage(data.waitingGames[i].itendedPlayers[j], "#game" + data.waitingGames[i].gameID, 80);
        }

        var freeSlots = data.waitingGames[i].nrOfPlayers - data.waitingGames[i].itendedPlayers.length;
        for (var k = 0; k < freeSlots; k++) {
            createImageFreeSlot(k, "#game" + data.waitingGames[i].gameID, 80);
        }
    }
}

function createImageFreeSlot(divId, appendTo, size, onClickFunction) {
    jQuery('<div/>', {
        class:divId + " profilePicWrapper",
        id:divId,
        onclick:onClickFunction
    }).appendTo(appendTo);

    jQuery('<img/>', {
        src:"img/fb_profile_default.png",
        style:"width:" + size + "px;"
    }).appendTo(appendTo + " ." + divId);
}

function createImage(uid, appendTo, size, klass) {
    jQuery('<div/>', {
        class:klass || uid + " profilePicWrapper"
    }).appendTo(appendTo);

    jQuery('<img/>', {
        src:getFBPictureUrlById(uid)
    }).appendTo(appendTo + " ." + uid);

    $image = jQuery(appendTo + " ." + uid + ' img');
    var width = $image.width();
    var height = $image.height();
    if (width > height) {
        $image.css({
            height:size + "px"
        });
    } else {
        $image.css({
            width:size + "px"
        });
    }
}

function joinGame(id) {
    window.location = conf.gameMultiplayerUrl + id;
}
function startNewGame() {
    $('#lobby .confirm-btn').remove();
    OurGame.newGameScreenContent = $('#lobby').html();
    OurGame.doNotShowSlider = true;
    initMultiplayerGame();
}
function removeLobbyHTML() {
    jQuery("#lobby .newGame").remove();
    jQuery("#lobby #nrOfRunning").remove();
    jQuery("#lobby #nrOfWaiting").remove();
    jQuery("#lobby #scro").remove();
}

function emptyLobby() {
    jQuery("#lobby").empty();
}

function removeLobby() {
    jQuery("#lobby").remove();
}
function createNewGameScreen() {
    emptyLobby();
    OurGame.newGameButtonPushed = true;

    // make gameId
    var currentDateTime = new Date();
    currentDateTime.setMinutes(currentDateTime.getMinutes() + 1);
    OurGame.gameID = md5('' + OurGame.UID + currentDateTime.getTime());

    jQuery('<h1/>').text("New Game").appendTo("#lobby");
    jQuery('<div/>', {class:"sliderWrapper"}).text("Choose nr of players:").appendTo("#lobby");
    jQuery('<input/>', {id:"slider", type:"slider", name:"players", value:"4"}).appendTo(".sliderWrapper");
    jQuery('<div/>', {id:'players'}).appendTo('#lobby');
    jQuery('<div/>', {class:'confirm-btn blue-btn', onclick:'startNewGame();'}).text('Start').appendTo('#lobby');
    jQuery("#slider").slider({to:9, from:2, step:1, skin:"round_plastic", limits:false, dimension:'', onstatechange:function (value) {
        sliderStateChanged(value);
    }});
}

var lastSliderState = null;
function sliderStateChanged(value) {
    if (lastSliderState == value) {
        return;
    }
    var divElements = jQuery("#players > div").size();
    var counter = divElements; // for classnames
    for (var i = 0; i < Math.abs(divElements - value); i++) {
        if (divElements > value) { // remove last element
            jQuery('#players div:last').remove();
            OurGame.playerUIDs.pop();
            counter--;
        }
        else { // add element
            counter++;
            if (lastSliderState == null) { // initiator is the first player
                createImage(OurGame.UID, '#players', 100);
                OurGame.playerUIDs[OurGame.playerUIDs.length] = OurGame.UID;
                lastSliderState = value;
            }
            else {
                createImageFreeSlot(counter, '#players', 100, "FBFriendSelectorDialog(" + counter + ")");
                // at first the UIDs will be empty
                OurGame.playerUIDs[OurGame.playerUIDs.length] = null;
            }
        }
    }
    // is done in the end so we know that this is the first time script is ran
    lastSliderState = value;
    OurGame.newGameScreenContent = $('#lobby').html();
}
function replaceEmptySlotWithFriend(emptyId, friendId) {
    createImage(friendId, '#players', 100);
    $('#players #' + emptyId).after($('.' + friendId));
    $('#players #' + emptyId).remove();
    OurGame.newGameScreenContent = $('#lobby').html();
}

function startGameWaitScreen(registeredPlayers, itendedPlayers, nrOfPlayers) {
    emptyLobby();
    OurGame.itendedPlayers = itendedPlayers;
    jQuery('<div/>', {id:'players'}).appendTo('#lobby');
    jQuery('<p/>').text("Joined players:").appendTo("#players");
    for (var i = 0; i < registeredPlayers.length; i++) {
        createImage(registeredPlayers[i], "#players", 80);
    }
    var itendedNOTregistered = getItendedNOTregisteredPlayers(registeredPlayers, itendedPlayers);
    for (var k = 0; k < itendedNOTregistered.length; k++) {
        createImage(itendedNOTregistered[k], "#players", 80, "itended  profilePicWrapper " + itendedNOTregistered[k]);
    }

    var freeSlots = nrOfPlayers - (registeredPlayers.length + itendedNOTregistered.length);
    for (var j = 0; j < freeSlots; j++) {
        createImageFreeSlot("free" + j, '#players', 80);
    }
}

function getItendedNOTregisteredPlayers(registeredPlayers, itendedPlayers) {
    var itendedNOTregistered = [];
    for (var i = 0; i < itendedPlayers.length; i++) {
        var itendedUID = Number(itendedPlayers[i]);
        var add = true;
        for (var j = 0; j < registeredPlayers.length; j++) {
            if (Number(registeredPlayers[j]) === itendedUID || itendedUID === Number(OurGame.UID)) {
                add = false;
                break;
            }
        }
        if (add) {
            itendedNOTregistered.push(String(itendedPlayers[i]));
        }
    }

    return itendedNOTregistered
}

function isItended(playerUID) {
    for (var i = 0; i < OurGame.itendedPlayers.length; i++) {
        if (Number(playerUID) === Number(OurGame.itendedPlayers[i])) {
            return true;
        }
    }
    return false;
}
function addJoinedPlayer(playerUID) {
    if (isItended(playerUID)) {
        jQuery('.' + String(playerUID)).remove();
    } else {
        var freeDivList = jQuery("div[id^='free']");
        jQuery(freeDivList[0]).remove();
    }
    createImage(playerUID, "#players", 80);
}

function addLeftPlayer(playerUID) {
    jQuery('.' + String(playerUID)).remove();
    if (isItended(playerUID)) {
        createImage(playerUID, "#players", 80, "itended  profilePicWrapper " + playerUID);
    } else {
        createImageFreeSlot("free" + playerUID, '#players', 80);
    }
}

function createSTARTButton() {
    jQuery('<div/>', {id:"startButton", class:'confirm-btn'}).appendTo("#lobby");
    jQuery('<input/>', {type:"submit", class: 'blue-btn', style:'width: 100px;', onclick:"startGame();", value:"START"}).appendTo("#startButton");
}
/**
 * Removes all content from lobby
 *
 * @param text
 */
function showInfoScreenInLobby(text) {
    emptyLobby();
    jQuery('<div/>', {
        id:"lobby-info"
    })
        .text(text)
        .appendTo('#lobby');
}

function _to_utf8(s) {
    var c, d = "";
    for (var i = 0; i < s.length; i++) {
        c = s.charCodeAt(i);
        if (c <= 0x7f) {
            d += s.charAt(i);
        } else if (c >= 0x80 && c <= 0x7ff) {
            d += String.fromCharCode(((c >> 6) & 0x1f) | 0xc0);
            d += String.fromCharCode((c & 0x3f) | 0x80);
        } else {
            d += String.fromCharCode((c >> 12) | 0xe0);
            d += String.fromCharCode(((c >> 6) & 0x3f) | 0x80);
            d += String.fromCharCode((c & 0x3f) | 0x80);
        }
    }
    return d;
}